package com.yunxi.filter;

import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.rpc.*;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.MDC;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * Created by xuruzi on 2019/3/25.
 *
 * dubbo配置filter
 * 1,在application.properties中配置过滤器
 * dubbo.com.fxtech.demo.provider.filter=dubboLogFilter
 *
 * 2,在resources/下新建目录 META-INF / dubbo /
 * 在此新建路径下创建纯文本文件com.alibaba.dubbo.rpc.Filter
 *
 * 3,在com.alibaba.dubbo.rpc.Filter文件中配置参数
 * dubboLogFilter=com.fxtech.demo.com.fxtech.demo.provider.DubboLogFilter
 *
 * 以上3步即可
 *
 */
@Activate
public class DubboLogFilter implements Filter{

    final String serverHost = NetUtils.getLocalHost();//当前服务器IP

    /**
     * Environment 可以当做application.properties
     */
    private Environment environment;

    /**
     * dubbo不用标注注解,只能通过setter方式注入bean
     * @param environment
     */
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        /**
         * 日志管理
         */
        Map<String,String> attachments = RpcContext.getContext().getAttachments();
        MDC.put("traceId", attachments.get("traceId"));
        MDC.put("serverHost",serverHost);
        MDC.put("applicationName", environment.getProperty("spring.application.name"));

        MDC.put("args", JSONArray.toJSONString(invocation.getArguments()));
        MDC.put("methodName", invocation.getMethodName());

        Result result = invoker.invoke(invocation);

        return result;
    }
}
